<?php

interface LogMethod {
	public function Log($message);
}

class Log_STDOUT implements LogMethod {
	public function Log($message) {
		print $message;
	}
}

class Log_Syslog implements LogMethod {
	private $ident;
	public function __construct($ident) {
		$this->ident = $ident;
	}
	
	public function Log($message) {
		$message = substr($message,0,500);	
		openlog($this->ident, LOG_PID, LOG_LOCAL0);
		syslog(LOG_NOTICE,$message);
	}

	public function __destruct() {
		closelog();
	}
}

class Log_File implements LogMethod {
	private $file;
	private $fh;

	public function __construct($file) {
		$this->file = $file;
		$this->fh = fopen($this->file,"a+");
	}

	public function Log($message) {
		fwrite($this->fh,$message."\n");
	}
	
	public function __destruct() {
		fclose($this->fh);
	}
}

class Log_Email implements LogMethod {
	private $email;
	
	public function __construct($email) {
		$this->email = $email;
	}
	public function Log($message) {
		mail($email,"jaskiewicz.kamil@gmail.com",$message);
	}
}

class Log {
	public $callers;
	private $logmethod;

	public function __construct(LogMethod $logmethod) {
		//TODO: accept multiple instances of LogMethod class 
		$this->callers = debug_backtrace();
		array_shift($this->callers);
		$this->logmethod = $logmethod;
	}
	
	public function getBacktrace() {
		foreach ($this->callers as $item) {
			$backtrace .= "$item[file]:$item[line]:";
			$backtrace .= "$item[function](";
			$args = 0;
			foreach ($item[args] as $arg) {
				if ($args)
					$backtrace .= ", ";
				$backtrace .= "'$arg'";
				$args++;
			}
			$backtrace .= ");\n\n";
		}
		try {
			if (is_array($_POST)) {
				foreach ($_POST as $key=>$value) {
					$post .= "\$$key = $value\n";
				}
			}		
			if (is_array($_GET)) {
				foreach ($_GET as $key=>$value) {
					$get .= "\$$key = $value\n";
				}
			}
			if (is_array($_SERVER)) {
				foreach ($_SERVER as $key=>$value) {
					$server .= "\$$key = $value\n";
				}
			}
			if (is_array($_SESSION)) {
				foreach ($_SESSION as $key=>$value) {
					if (!is_object($value)) $session .= "\$$key = $value\n";
				}
			}
		}
		catch (Exception $e) {
			// Do nothing
		}
		return array($backtrace,array("POST" => $post,"GET" => $get,"SERVER" => $server,"SESSION" => $session));
	}

	public function Log($message="") {
		$this->logmethod->Log($message);
	}

}

?>
